#include "likedatabase.h"
#include <QTime>
#include <QMessageBox>
#include <QDebug>

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>

LikeDatabase::LikeDatabase()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("ChatUI");
    if(!db.open()){
        QMessageBox::critical(0, "严重错误！", "数据库(QSQLITE)打开失败!");
        exit(1);
    }

    QSqlQuery query;
    if(query.exec("SHOW DATABASES")){
        while(query.next()){
            qDebug() << query.value(0).toString();
        }
    }

    //查询表是否存在，不存在就创建
    query.exec("SELECT * FROM sqlite_master WHERE NAME = 'friend'");
    if(!query.next()){
        QString queryString("CREATE TABLE friend (\
                            uuid VARCHAR(32) PRIMARY KEY,\
                            name VARCHAR(32) NOT NULL,\
                            netName VARCHAR(32) NOT NULL)");
        if(query.exec(queryString)){
            /****************************测试用代码************************/
            query.exec("INSERT INTO friend VALUES('qwerq82j38dss99dks72h3ie0ssdfvcd', '张三', '我不是张三')");
            query.exec("INSERT INTO friend VALUES('qwerqh27sy6w7eujyhtgrfedbvcftdwq', '李四', '我不是李四')");
            query.exec("INSERT INTO friend VALUES('qwergrqerger9jw7dj287dj37dg2s71g', '王五', '我不是王五')");
            query.exec("INSERT INTO friend VALUES('s46sd7s7ds88s8ds8ds7jdfgsderqwer', '沈六', '我不是沈六')");
            query.exec("INSERT INTO friend VALUES('erwwerne82823u382392kkk32hlrqwer', '赵七', '我不是赵七')");
        }
        else{
            QSqlError error = query.lastError();
            qDebug() << "error.databaseText() : " << error.databaseText();
            qDebug() << "error.drivertext() : " << error.driverText();
            qDebug() << "数据库没有表friend,并且创建失败!";
            exit(1);
        }
    }
    //创建聊天记录数据表，因为数据较少所以只存一张表中，isSend表示是发出还是收到
    query.exec("SELECT * FROM sqlite_master WHERE NAME = 'chatRecord'");
    if(!query.next()){
        QString queryString("CREATE TABLE chatRecord (\
                            uuid VARCHAR(32),\
                            isSend BIT NOT NULL,\
                            recordDate DATETIME NOT NULL,\
                            textRecord VARCHAR(255) )");
        if(!query.exec(queryString)){
            QSqlError error = query.lastError();
            qDebug() << "error.databaseText() : " << error.databaseText();
            qDebug() << "error.drivertext() : " << error.driverText();
            qDebug() << "数据库中没有表，并且创建表 chatRecord 失败!";
            exit(1);
        }
    }
}

QVector<QPair<QString, QString> > LikeDatabase::getAllUuidAndName()
{
    QVector<QPair<QString, QString>> vector;
    QSqlQuery query;
    query.setForwardOnly(true);
    if(query.exec("SELECT uuid, name FROM friend")){
        while(query.next()){
            vector.push_back(QPair<QString, QString>(query.value(0).toString(), query.value(1).toString()));
        }
    }
    else{
        QSqlError error = query.lastError();
        qDebug() << "error.databaseText() : " << error.databaseText();
        qDebug() << "error.drivertext() : " << error.driverText();
        qDebug() << "getAllUuidAndName() 失败!";
        exit(1);
    }
    return vector;
}

//插入聊天记录
void LikeDatabase::addMessage(const QString &uuid, const QString &message, bool isSend)
{
    QSqlQuery query;
    bool queryIsRight = query.exec(QString("INSERT INTO chatRecord(uuid, isSend, recordDate, textRecord) \
                       VALUES('%1', '%2', datetime('now','localtime'), '%3')")
                       .arg(uuid).arg(isSend).arg(message));
    if(!queryIsRight){
            QSqlError error = query.lastError();
            qDebug() << "error.databaseText() : " << error.databaseText();
            qDebug() << "error.drivertext() : " << error.driverText();
            qDebug() << "addMessage() 失败!";
    }
}

void LikeDatabase::addNewFriend(const QString &uuid, const QString &netName, const QString &name)
{
    QString thisName;
    name.isEmpty() ? (thisName = netName) : (thisName = name);

    QSqlQuery query;
    bool queryIsRight = query.exec(QString("INSERT INTO friend (uuid, name, netName) VALUES('%1', '%2', '%3')")
                        .arg(uuid).arg(thisName).arg(netName));
    if(!queryIsRight){
        QSqlError error = query.lastError();
        qDebug() << "error.databaseText() : " << error.databaseText();
        qDebug() << "error.drivertext() : " << error.driverText();
        qDebug() << "addNewFriend() 失败!";
    }
}

void LikeDatabase::updateFriendNetName(const QString &uuid, const QString &netName)
{
    QSqlQuery query;
    bool queryIsRight = query.exec(QString("UPDATE friend SET netName = '%1' WHERE uuid = '%2'")
                                   .arg(netName).arg(uuid));
    if(!queryIsRight){
        QSqlError error = query.lastError();
        qDebug() << "error.databaseText() : " << error.databaseText();
        qDebug() << "error.drivertext() : " << error.driverText();
        qDebug() << "updateFriendNetName() 失败!";
    }
}

void LikeDatabase::updateFriendName(const QString &uuid, const QString &name)
{
    QSqlQuery query;
    bool queryIsRight = query.exec(QString("UPDATE friend SET name = '%1' WHERE uuid = '%2'")
                                   .arg(name).arg(uuid));
    if(!queryIsRight){
        QSqlError error = query.lastError();
        qDebug() << "error.databaseText() : " << error.databaseText();
        qDebug() << "error.drivertext() : " << error.driverText();
        qDebug() << "updateFriendName() 失败!";
    }
}

QStringList LikeDatabase::getTopTenMessage(const QString &uuid)
{
    QSqlQuery query;
    query.setForwardOnly(true);
    if(!query.exec(QString("SELECT name FROM friend WHERE uuid = '%1'").arg(uuid))){
        return QStringList();
    }
    query.next();
    QString friendName = query.value(0).toString();

    bool queryIsRight = query.exec(QString("SELECT isSend, recordDate, textRecord FROM chatRecord WHERE uuid = '%1' ORDER BY recordDate LIMIT 10")
                                   .arg(uuid));
    if(!queryIsRight){
        QSqlError error = query.lastError();
        qDebug() << "error.databaseText() : " << error.databaseText();
        qDebug() << "error.drivertext() : " << error.driverText();
        qDebug() << "getTopTenMessage(const QString &uuid) 失败!";
        return QStringList();
    }

    QStringList list;
    while(query.next()){
        if(query.value(0).toBool()){
            list.append(QString("我  %1\n    %2")
                        .arg(query.value(1).toString()).arg(query.value(2).toString()));
        }
        else{
            list.append(QString("%1  %2\n    %3").arg(friendName)
                        .arg(query.value(1).toString()).arg(query.value(2).toString()));
        }
    }
    return list;
}

QStringList LikeDatabase::getAllMessage(const QString &uuid)
{
    QSqlQuery query;
    query.setForwardOnly(true);
    if(!query.exec(QString("SELECT name FROM friend WHERE uuid = '%1'").arg(uuid))){
        return QStringList();
    }
    query.next();
    QString friendName = query.value(0).toString();

    bool queryIsRight = query.exec(QString("SELECT isSend, recordDate, textRecord FROM chatRecord WHERE uuid = '%1' ORDER BY recordDate")
                                   .arg(uuid));
    if(!queryIsRight){
        QSqlError error = query.lastError();
        qDebug() << "error.databaseText() : " << error.databaseText();
        qDebug() << "error.drivertext() : " << error.driverText();
        qDebug() << "getTopTenMessage(const QString &uuid) 失败!";
        return QStringList();
    }

    QStringList list;
    while(query.next()){
        if(query.value(0).toBool()){
            list.append(QString("我  %1\n    %2")
                        .arg(query.value(1).toString()).arg(query.value(2).toString()));
        }
        else{
            list.append(QString("%1  %2\n    %3").arg(friendName)
                        .arg(query.value(1).toString()).arg(query.value(2).toString()));
        }
    }
    return list;
}

void LikeDatabase::deleteFriend(const QString &uuid)
{
    this->deleteFriendChatRecord(uuid);
    QSqlQuery query;
    if(!query.exec(QString("DELETE FROM friend WHERE uuid = '%1'").arg(uuid))){
        QSqlError error = query.lastError();
        qDebug() << "error.databaseText() : " << error.databaseText();
        qDebug() << "error.drivertext() : " << error.driverText();
        qDebug() << "deleteFriend(const QString &uuid) 失败!";
    }
}

void LikeDatabase::deleteFriendChatRecord(const QString &uuid)
{
    QSqlQuery query;
    if(!query.exec(QString("DELETE FROM chatRecord WHERE uuid = '%1'").arg(uuid))){
        QSqlError error = query.lastError();
        qDebug() << "error.databaseText() : " << error.databaseText();
        qDebug() << "error.drivertext() : " << error.driverText();
        qDebug() << "deleteFriendChatRecord(const QString &uuid) 失败!";
    }
}

